package com.och.mrcp.service;

import com.och.mrcp.handler.VoiceRecognitionSessionHandler;
import com.och.mrcp.core.rtp.session.RtpSessionManager;
import com.och.mrcp.core.sip.transaction.SipTransactionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 应用生命周期管理器
 * 确保应用关闭时所有组件都能正确清理资源
 */
@Slf4j
@Component
public class ApplicationLifecycleManager {
    
    @Autowired
    private VoiceRecognitionSessionHandler voiceRecognitionSessionHandler;
    
    @Autowired
    private MediaSessionManager mediaSessionManager;
    
    @Autowired
    private RtpSessionManager rtpSessionManager;
    
    @Autowired
    private UnifiedVoiceSessionManager unifiedVoiceSessionManager;
    
    @Autowired
    private SipTransactionManager sipTransactionManager;
    
    /**
     * 应用关闭时的清理操作
     * 确保所有会话和资源都被正确释放
     */
    @EventListener(ContextClosedEvent.class)
    public void onApplicationShutdown(ContextClosedEvent event) {
        log.info("Application shutdown initiated, starting cleanup process...");
        
        try {
            // 1. 首先清理语音识别会话
            log.info("Cleaning up voice recognition sessions...");
            voiceRecognitionSessionHandler.cleanup();
            
            // 2. 清理统一语音会话管理器
            log.info("Cleaning up unified voice session manager...");
            unifiedVoiceSessionManager.cleanupAllSessions();
            
            // 3. 清理媒体会话
            log.info("Cleaning up media sessions...");
            mediaSessionManager.logActiveSessions();
            // MediaSessionManager 没有专门的清理方法，但有 @PreDestroy
            
            // 4. 清理RTP会话
            log.info("Cleaning up RTP sessions...");
            rtpSessionManager.cleanupAllSessions();
            
            // 5. 清理SIP事务
            log.info("Cleaning up SIP transactions...");
            sipTransactionManager.cleanupExpiredTransactions();
            
            log.info("Application cleanup completed successfully");
            
        } catch (Exception e) {
            log.error("Error during application shutdown cleanup: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 获取当前活跃会话统计信息
     */
    public void logSystemStatus() {
        log.info("=== System Status ===");
        log.info("Active voice recognition sessions: {}", voiceRecognitionSessionHandler.getActiveSessionCount());
        log.info("RTP session info: {}", rtpSessionManager.getServiceInfo());
        log.info("Voice session manager info: {}", unifiedVoiceSessionManager.getServiceInfo());
        mediaSessionManager.logActiveSessions();
        log.info("=== End System Status ===");
    }
}
